<?php
    /**
     * Created by PhpStorm.
     * User: jackhhy
     * Date: 2019/7/4-11:08
     * Link: https://gitee.com/luckygyl/lucky_admin
     * FileName: Setting.php
     * Keys: ctrl+alt+L/ctrl+s(代码格式化) ctrl+J(代码提示) ctrl+R(替换)ALT+INSERT(生成代码(如GET,SET方法,构造函数等) , 光标在类中才生效)
     * CTRL+ALT+O (优化导入的类和包 需要配置) SHIFT+F2(高亮错误或警告快速定位错误)
     * CTRL+SHIFT+Z(代码向前) CTRL+SHIFT+/ (块状注释) ctrl+shift+enter(智能完善代码 如if())
     */

    namespace app\admin\controller;

    use app\admin\validate\Aadmimember;
    use service\TreeService;
    use service\UtilService;
    use think\Exception;
    use think\Validate;

    class Setting extends SystemBase
    {

        protected $admin_member_model;
        protected $admin_role;
        protected $setting;

        protected function _initialize()
        {
            parent::_initialize(); // TODO: Change the autogenerated stub
            $this->admin_member_model = new \app\admin\model\AdminMember();//后台管理员
            $this->admin_role         = new \app\admin\model\AdminRole();//角色模型
            $this->setting            = db("setting");
        }

        /**
         * @return mixed
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: Jackhhy <jackhhy520@qq.com>
         * @name: MyInfo
         * @describe:我的基本资料
         */
        public function MyInfo()
        {
            if($this->request->isAjax()) {
                $data = $this->request->post();
                //dump($data);die;
                try {
                    $valdata = new Aadmimember();//实例化验证器
                    //验证数据合法性
                    if(!$valdata->check($data)) {
                        $this->error('提交失败：'.$valdata->getError());
                    }

                    $res = $this->admin_member_model->editData($data);//编辑数据

                    if($res!==false) {
                        $ars = ['describe' => '修改我的基本资料', 'type' => 2, 'admin_name' => self::$admin_info['username'], 'browse' => UtilService::getBrowser(), 'model' => self::$mode_name, 'controller' => self::$controller_name, 'action' => self::$action_name];
                        AddLogs($ars); //添加操作日志
                         $this->success("修改成功");
                    }
                    else {
                         $this->error("修改失败");
                    }
                } catch (Exception $exception) { //捕获异常
                     $this->error($exception->getMessage());
                }
            }

            $tree = TreeService::toFormatTree($this->admin_role->GetRoleList(), "name");//获取角色
            $this->assign(compact("tree"));
            return $this->fetch();
        }



        /**
         * @return mixed
         * @author: Jackhhy <jackhhy520@qq.com>
         * @name: MyPass
         * @describe:修改我的密码
         */
        public function MyPass()
        {
            if($this->request->isAjax()) {
                $data     = $this->request->post();
                $validate = new Validate([['oldpassword|token', 'alphaNum', '密码只允许字母、数字'], ['password', 'min:6|max:16|alphaNum', '密码最少6个字符|密码最长16个字符|密码只允许字母、数字'], ['repassword', 'confirm:password', '两次密码输入不一致'],]);

                //校验数据
                if(!$validate->check($data)) {
                    $this->error($validate->getError());
                }

                $pass = UtilService::think_decrypt(self::$admin_info['password']);
                if($pass!=$data['oldpassword']) {
                    $this->error("当前密码输入错误");
                }
                unset($data['oldpassword']);
                unset($data['repassword']);

                $res = $this->admin_member_model->editData($data);//编辑数据

                if($res!==false) {
                    $ars = ['describe' => '修改我的密码', 'type' => 2, 'admin_name' => self::$admin_info['username'], 'browse' => UtilService::getBrowser(), 'model' => self::$mode_name, 'controller' => self::$controller_name, 'action' => self::$action_name];
                    AddLogs($ars); //添加操作日志
                     $this->success("修改成功");
                }
                else {
                     $this->error("修改失败");
                }
            }

            return $this->fetch();
        }



        /**
         * @return mixed
         * @author: Jackhhy <jackhhy520@qq.com>
         * @name: site
         * @describe:网站设置
         */
        public function site()
        {
            if($this->request->isAjax()) {
                $data = $this->request->post();
                foreach($data as $k => $v){
                    $res = $this->setting->where("key", $k)->setField("value", $v);
                }
                $ars = ['describe' => '设置网站信息', 'type' => 2, 'admin_name' => self::$admin_info['username'], 'browse' => UtilService::getBrowser(), 'model' => self::$mode_name, 'controller' => self::$controller_name, 'action' => self::$action_name];
                AddLogs($ars); //添加操作日志
                $this->success("提交成功");
            }
            $this->assign("info", self::$setting_config);
            return $this->fetch();
        }


        /**
         * @return mixed
         * @author: Jackhhy <jackhhy520@qq.com>
         * @name: safe
         * @describe:安全设置
         */
        public function safe()
        {
            if($this->request->isAjax()) {
                $data = $this->request->post();
                $res  = $this->setting->where("key", "safe")->setField("value", json_encode($data['safe']));
                //dump($data);
                $ars = ['describe' => '网站安全设置', 'type' => 2, 'admin_name' => self::$admin_info['username'], 'browse' => UtilService::getBrowser(), 'model' => self::$mode_name, 'controller' => self::$controller_name, 'action' => self::$action_name];
                AddLogs($ars); //添加操作日志
                $res ? $this->success("提交成功") : $this->error("提交失敗");
            }

            // dump(self::$setting_config);
            $this->assign("safe", self::$setting_config['safe']);
            return $this->fetch();
        }



        /**
         * @return mixed
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: Jackhhy <jackhhy520@qq.com>
         * @name: email
         * @describe:邮箱设置
         */
        public function email()
        {
            if($this->request->isPost()) {
                $post = $this->request->post();
                // dump($post);die;
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new Validate([['from_email', 'require|email', '发件箱不能为空|发件箱格式不正确'], ['from_name', 'require', '发件人不能为空'], ['smtp', 'require', '邮箱smtp服务器不能为空'], ['username', 'require|email', '登录账户不能为空|登录账户应为邮箱格式'], ['password', 'require', '登录密码不能为空'], ['content', 'require', '邮件模板不能为空'],]);
                //验证部分数据合法性
                if(!$validate->check($post['email'])) {
                    $this->error('提交失败：'.$validate->getError());
                }

                $data = json_encode($post['email']);
                $res  = \app\admin\model\Setting::update(['value' => $data], ['key' => 'email']);
                if($res==false) {
                    $ars = ['describe' => '邮箱设置', 'type' => 2, 'admin_name' => self::$admin_info['username'], 'browse' => UtilService::getBrowser(), 'model' => self::$mode_name, 'controller' => self::$controller_name, 'action' => self::$action_name];
                    AddLogs($ars); //添加操作日志
                    $this->error("修改失败");
                }
                else {
                    $this->success("修改成功");
                }
            }

            /*  $s=new \app\admin\model\Setting();
              dump($s->getSetting());*/
            $res = db("setting")->where("key", "email")->find();
            //dump(json_decode($res['value']));
            $this->assign("info", json_decode($res['value']));
            return $this->fetch();
        }


        /**
         * @return mixed|void
         * @throws \phpmailerException
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: Jackhhy <jackhhy520@qq.com>
         * @name: mailto
         * @describe:发送邮件测试
         */
        public function mailto()
        {
            if($this->request->isPost()) {
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new Validate([['email', 'require|email', '收件箱不能为空|收件箱格式不正确'],]);
                //验证部分数据合法性
                if(!$validate->check($post)) {
                    $this->error('提交失败：'.$validate->getError());
                }

                $address = $post['email'];
                $mailto  = SendMail($address);
                if(false==$mailto) {
                     $this->error('发送失败');
                }
                else {
                      $ars = ['describe' => '发送测试邮件', 'type' => 2, 'admin_name' => self::$admin_info['username'], 'browse' => UtilService::getBrowser(), 'model' => self::$mode_name, 'controller' => self::$controller_name, 'action' => self::$action_name];
                      AddLogs($ars); //添加操作日志
                     $this->success('邮件发送成功');
                }
            }
            else {
                return $this->fetch();
            }
        }


    }